iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 11
0
Modern Web

用30days 了解web系列 第 11

(Day 11) Laravel Relational Database

  • 分享至 

  • xImage
  •  

Database tables are mean to be related to one another, for example, a blog post could have many comments this is called one-to-many relationship. in Laravel Eloquent makes managing and working with these relationships easily and support several types of relationships.

today's article will cover these following type of relationships:

  1. One to One
  2. One to Many
  3. Many to Many

One to One
one to one is the basic relation between databases. for example, a user might be associated with one phone.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get the phone record associated with the user.
     */
    public function phone()
    {
        return $this->hasOne('App\Models\Phone');
    }
}

we put Phone inside the User model, and that is how we define One to one relationships.

One to Many
One to Many is used to define relationships where a single model is related to any amount of other models. as we said earlier one blog post may have many comments.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function comments()
    {
        return $this->hasMany('App\Models\Comment');
    }
}

we use hasMany for one to many relationships.

Many to Many
this relation is slightly special if you compare it to the other. for example, the relation between the book and the author is called many to many relationships, because a book may have many authors and vice-versa.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    /**
     * The book that belong to the authors.
     */
    public function author()
    {
        return $this->belongsToMany('App\Models\Author');
    }
}

we use the belongToMany Method for many to many relationships.

Inverted Relationship
for the inverted relationship between One to One and One to Many relationships, belongsTo method is used.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    /**
     * Get the post that owns the comment.
     */
    public function post()
    {
        return $this->belongsTo('App\Models\Post');
    }
}

上一篇
(Day 10) Laravel Auth and JWT
下一篇
(day 12) Introduction to Basic GIT
系列文
用30days 了解web30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言